﻿using System;
using System.Collections.Generic;

namespace Zero
{
    /// <summary>
    /// 服务定位器
    /// </summary>
    public static class ServiceLocator
    {
        private static readonly IDictionary<Type, object> s_services = new Dictionary<Type, object>();

        /// <summary>
        /// 注册服务
        /// </summary>
        /// <param name="service">服务对象</param>
        /// <typeparam name="T">服务类型</typeparam>
        public static void Register<T>(T service)
        {
            if (!s_services.ContainsKey(typeof(T)))
            {
                s_services[typeof(T)] = service;
            }
        }

        /// <summary>
        /// 注销服务
        /// </summary>
        /// <typeparam name="T">服务类型</typeparam>
        public static void Unregister<T>()
        {
            s_services.Remove(typeof(T));
        }

        /// <summary>
        /// 注销所有服务
        /// </summary>
        public static void UnregisterAll()
        {
            s_services.Clear();
        }

        /// <summary>
        /// 获取服务
        /// </summary>
        /// <typeparam name="T">服务类型</typeparam>
        /// <returns></returns>
        /// <exception cref="NotImplementedException">未实现</exception>
        public static T Get<T>()
        {
            return s_services.TryGetValue(typeof(T), out var result)
                ? (T)result
                : throw new NotImplementedException();
        }
    }
}
